import React, { useEffect, useState } from 'react';
import cn from 'classnames';
import s from './style.module.css';
import i from '@/index.module.css';

import BreadCrumb from '@/components/BreadCrumb';
import {
  Table,
  Message,
  Input,
  Button,
  Confirm,
  Tooltip,
  Pagination,
  Select,
  Loading,
} from '@knownsec/react-component';
import { exportGET, exportDEL, exportDownload } from '~/API';
import moment from 'moment';
const defaultInfo = {
  page: 1,
  limit: 10,
  target_url: '',
  status: '',
};
let set = null;
export default function backupRecovery() {
  const [tableData, setTableData] = useState({ data: [], total: 0 });
  const [selTable, setSelTable] = useState([]);
  const [searchInfo, setSearchInfo] = useState(defaultInfo);
  const [loading, setLoading] = useState(false);
  const [isContinue, setIsContinue] = React.useState(false);
  const [downlog, setDownlog] = useState('');
  const statusObj = {
    waiting: '等待中',
    pending: '进行中',
    success: '成功',
    failed: '失败',
  };
  const columns = [
    {
      title: '任务ID',
      dataIndex: 'export_task_id',
    },
    {
      title: '业务系统',
      dataIndex: 'targets',
      render: (e) => {
        const dome = () => {
          let text = e.length > 1 ? `等${e.length}个业务系统` : '';
          return (
            <div className={cn(i.df, i.fdc, s.targets)}>
              <span className={s.url}>
                <span className={i.ell} style={{ width: e.length > 1 ? '60%' : '100%' }}>
                  {e[0].target_url || '- -'}
                </span>
                <span>{text}</span>
              </span>
              <span className={cn(i.ell,s.name)}>{e[0].target_name || '- -'}</span>
            </div>
          );
        };
        if (e) {
          if (e.length > 0) {
            return (
              <Tooltip
                overlay={
                  <div>
                    <p style={{ 'max-width': '50vw' }}>
                      系统地址：{e.map((e_, i) => {
                        return e_.target_url + (i === e.length - 1 ? '' : '，');
                      })}
                    </p>
                    <p>系统名称：{e[0].target_name}</p>
                  </div>
                }
                placement="top"
              >
                {dome()}
              </Tooltip>
            );
          } else {
            return (
              <div className={cn(i.df, i.fdc, s.targets)}>
                <span className={s.url}>- -</span>
                <span>- -</span>
              </div>
            );
          }
        }
      },
    },
    {
      title: '任务下发时间',
      dataIndex: 'task_created_at',
      render: (value) => (value ? moment(value).format('YYYY-MM-DD HH:mm:ss') : '- -'),
    },
    {
      title: '监测时间范围',
      dataIndex: 'monitored_at',
      render: (value) => {
        const { start_at, end_at } = value;
        if (start_at && end_at) {
          return (
            <>
              <p>{moment(start_at).format('YYYY-MM-DD HH:mm:ss')}</p>
              <p>{moment(end_at).format('YYYY-MM-DD HH:mm:ss')}</p>
            </>
          );
        } else {
          return (
            <Tooltip overlay={'下载当时最新一次监测结果'} placement="topLeft">
              <p>
                <p>- -</p>
                <p>- -</p>
              </p>
            </Tooltip>
          );
        }
      },
    },
    {
      title: '生成时间',
      dataIndex: 'report_created_at',
      render: (value) => (value ? moment(value).format('YYYY-MM-DD HH:mm:ss') : '- -'),
    },
    {
      title: '状态',
      dataIndex: 'status',
      className: s.w_8r,
      render: (e, row) => {
        const t = statusObj[e];
        const p = row.progress;
        const color = {
          success: '#6AAC42',
          failed: '#D0021B',
        };
        return (
          <p>
            <span style={{ color: color[e] }}>{t}</span>
            {e === 'pending' && <span className={i.ml5}>{p}%</span>}
          </p>
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      className: s.w_8r,
      render: (e, row) => {
        const id = row.export_task_id;
        return (
          <div>
            {row.status === 'success' && (
              <span
                className={s.operation}
                style={{ color: downlog === id ? '#ccc' : '#0b6fd6' }}
                onClick={async () => {
                  if (downlog) {
                    return false;
                  }
                  setDownlog(id);
                  const res = await exportDownload({ export_task_id: id });
                  console.log('[ res ]-61', res);
                  setDownlog('');
                }}
              >
                {downlog === id ? '下载中' : '下载'}
              </span>
            )}
            <span
              className={s.operation}
              onClick={() => {
                delList([id]);
              }}
            >
              删除
            </span>
          </div>
        );
      },
    },
  ];
  const onSearch = (e) => {
    console.log('[ e ]-163', e);
    const searchInfo_ = { ...searchInfo, ...e };
    console.log('[ searchInfo_ ]-164', searchInfo_);
    setSearchInfo(searchInfo_);
    getList(searchInfo_);
  };
  const delList = (e) => {
    console.log('[  ]-120', e, selTable);
    Confirm({
      pro: true,
      title: '提示',
      message: <div className="confirmbox">您确认要删除选择的下载任务？</div>,
      onconfirm: async () => {
        const params = {
          export_task_ids: e || selTable,
        };
        const res = await exportDEL(params);
        getList(searchInfo);
        if (res.status === 'success') {
          setSelTable([]);
          Message.show({
            pro: true,
            showClose: false,
            type: 'success',
            message: '删除成功',
          });
        }
      },
      oncancel: () => {},
    });
  };
  const getList = async (e) => {
    setSelTable([]);
    const list = await exportGET(e);
    const data = list.data.data.map((e) => {
      return { ...e, id: e.export_task_id };
    });
    if (!data[0] && e.page > 1) {
      getList({ ...e, page: e.page - 1 });
      setSearchInfo({ ...searchInfo, page: e.page - 1 });
    }
    const some = data.some((row) => {
      if (row.status === 'pending' || row.status === 'waiting') {
        return true;
      }
    });
    clearTimeout(set);
    setIsContinue(some);
    setTableData({ data, total: list.data.total });
    setLoading(false);
  };
  // 轮询状态
  useEffect(() => {
    console.log('[  ]-213', isContinue);
    // clearTimeout(set);
    if (isContinue) {
      setIsContinue(false);
      clearTimeout(set);
      set = setTimeout(() => {
        console.log('[  ]-221', searchInfo);
        onSearch();
      }, 10 * 1000);
    }
  }, [isContinue]);
  useEffect(() => {
    setLoading(true);
    onSearch(defaultInfo);
  }, []);
  return (
    <>
      <BreadCrumb arr={[{ link: '', name: '报告下载', active: true }]} />
      <div className={s.backupRecovery}>
        <div className={s.bBox}>
          <div className={s.toolBox}>
            <Button
              type="text"
              onClick={() => {
                delList();
              }}
              disabled={!selTable.length}
            >
              删除
            </Button>
            <div className={s.tool}>
              <Select
                pro
                value={[searchInfo.status]}
                placeholder="状态"
                option={[
                  { label: '等待中', value: 'waiting' },
                  { label: '进行中', value: 'pending' },
                  { label: '成功', value: 'success' },
                  { label: '失败', value: 'failed' },
                ]}
                clearable
                className={s.sel}
                onChange={({ selectedItem }) => {
                  const e = selectedItem[0]?.value || '';
                  setSearchInfo({ ...searchInfo, status: e });
                  onSearch({ status: e });

                  getList({ ...searchInfo, status: e });
                }}
              />
              <Input
                pro
                value={searchInfo.target_url}
                search
                autoComplete={'off'}
                clear
                onSearch={(e) => {
                  onSearch({ target_url: e.value });
                }}
                className={cn('search-button')}
                placeholder="请输入业务系统地址"
                maxlength={32}
                onChange={(e) => {
                  console.log('[ e ]-200', e);
                  if (!e.value) {
                    onSearch({ target_url: e.value });
                  }
                  setSearchInfo({ ...searchInfo, target_url: e.value });
                }}
              />
            </div>
          </div>
          <Table
            columns={columns}
            selectable
            className={s.table}
            tableLoading={loading}
            loadingLabel=""
            data={tableData.data}
            getCheckedList={(e) => {
              setSelTable(e);
            }}
          ></Table>
          {tableData.total > 10 && (
            <Pagination
              key={Number(123)}
              className={s.pagination}
              current={searchInfo.page}
              showQuickJumper={{ goButton: true }}
              showSizeChanger={true}
              showTotal={(total) => `共${total}条`}
              pageSize={searchInfo.limit}
              pageSizeOptions={['10', '20', '50']}
              total={tableData.total}
              onChange={(page, limit) => {
                onSearch({ page, limit });
              }}
            />
          )}
        </div>
      </div>
    </>
  );
}
